#pragma once
#include <iostream>
#include <memory>
////////////////////////////////
#include "InetAddr.hpp"
#include "log.hpp"
#include "Socket.hpp"

using namespace socket_ns;

class SelectServer
{
    const static int N = sizeof(fd_set) * 8;
    const static int defaultfd = -1;

public:
    SelectServer(uint16_t port)
        : _port(port), _listenSocket(std::make_unique<Tcpsocket>())
    {
        InetAddr addr("0",_port);
        _listenSocket->BuildListenSocket(addr);
        for (int i = 0; i < N; i++)
        {
            _fd_array[i] = defaultfd; // 初始化所有数组下标fd
        }
        _fd_array[0] = _listenSocket->SockFd();
        std::cout<<"1"<<std::endl;
    }
    ~SelectServer()
    {
    }
    void AcceptClient()
    {
        InetAddr Clientaddr;
        int sockfd = _listenSocket->Accepter(&Clientaddr);
        if (sockfd < 0)
        {
            return;
            LOG(WARNING, "SOCKET CREATE ERROR");
        }
        LOG(INFO, "GET NEW LINK sockfd:%s,Client IP:%s,Port:%s ", sockfd, Clientaddr.Ip().c_str(), Clientaddr.Port());
        // 把新增的sockfd添加进辅助数组
        int pos = 1;
        for (; pos < N; pos++)
        {
            if (_fd_array[pos] == defaultfd)
                break; // 找到pos为未添加状态
        }
        if (pos == N) // 满
        {
            ::close(sockfd);
            LOG(DEBUG, "server is full!!!");
            return;
        }
        else // 处理
        {
            _fd_array[pos] = sockfd;
            LOG(DEBUG, "sockfd%d,Add into Select array", sockfd);
        }
        LOG(DEBUG, "current fd_array[] fd is%s\n", sockfd);
    }
    void ServiceIo(int pos) // 收发
    {
        char buffer[1024];
        ssize_t n = ::recv(_fd_array[pos], buffer, sizeof(buffer) - 1, 0);
        if (n > 0) // 收到了
        {
            buffer[n] = 0;
            std::cout << "Client say" << buffer << std::endl;
            std::string echo_string = "[server echo]:";
            echo_string += buffer;
            ::send(_fd_array[pos], echo_string.c_str(), echo_string.size(), 0);
        }
        else if (n == 0)
        {
            LOG(DEBUG, "fd:%d is closed", _fd_array[pos]);
            ::close(_fd_array[pos]);
            _fd_array[pos] = defaultfd; // 重置
            LOG(DEBUG, "reset fd_array fd_list%s", RfdsToString());
        }
        else
        {
            LOG(DEBUG, "fd:%d recv error", _fd_array[pos]);
            ::close(_fd_array[pos]);
            _fd_array[pos] = defaultfd; // 重置
            LOG(DEBUG, "reset fd_array fd_list%s", RfdsToString());
        }
    }
    void HandlerEvent(fd_set &rfds)
    {
        for (int i = 0; i < N; i++)
        {
            if (_fd_array[i] == defaultfd)
                continue;
            if (FD_ISSET(_fd_array[i], &rfds))
            {
                if (_fd_array[i] == _listenSocket->SockFd())
                {
                    AcceptClient(); // 创建新的套接字
                }
                else
                {
                    ServiceIo(i); // i这里就是当前的socket文件描述符
                }
            }
        }
    }

    void Loop()
    {
        while (true)
        {
            // 每次都要重新创建select 以便重新添加listensocket到select
            fd_set rfds;
            FD_ZERO(&rfds);
            int max_fd = defaultfd;
            for (int i = 0; i < N; i++)
            {
                if (_fd_array[i] == defaultfd)
                    continue;
                FD_SET(_fd_array[i], &rfds);
                if (max_fd < _fd_array[i])
                {
                    max_fd = _fd_array[i];
                }
            }

            struct timeval timeout = {0, 3}; // 00非阻塞

            int n = select(max_fd + 1, &rfds, nullptr, nullptr, &timeout);
            switch (n)
            {
            case 0:
                LOG(INFO, "timeout, %d.%d\n", timeout.tv_sec, timeout.tv_usec);
                break;
            case -1:
                LOG(ERROR, "select error...\n");
                break;
            default:
                LOG(DEBUG, "Event Happen. n : %d\n", n); // 底层有一个事件就绪，select为什么会一直通知我？因为：我们没有处理！
                HandlerEvent(rfds);
                break;
            }
        }
    }
    std::string RfdsToString()
    {
        std::string fdstr;
        for (int i = 0; i < N; i++)
        {
            if (_fd_array[i] == defaultfd)
                continue;
            fdstr += std::to_string(_fd_array[i]);
            fdstr += " ";
        }
        return fdstr;
    }

private:
    std::unique_ptr<Socket> _listenSocket;
    uint16_t _port;
    int _fd_array[N];
};